package engine;
import java.io.File;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import engine.dataobjects.MailItem;
import engine.scheduler.jobs.IMailItemJob;
import engine.scheduler.jobs.IMailItemJobDetail;
import engine.services.IDataResource;
import engine.services.IMailService;



public class Main {

    public static Log log = LogFactory.getLog(Main.class);
    public static final String DEBUG_OPTION = "debug";
    public static final String NOW_OPTION = "now";
    public static final String HELP_OPTION = "help";
	
    
    static Scheduler scheduler;
    static ApplicationContext context;
    /***
     * add options:
     * 
     * -debug
     * -filter [filter for name]
     * -now
     * -help
     * 
     * @param args
     */
	public static void main(String[] args){
		
		Options options = new Options();
		options.addOption(DEBUG_OPTION, false, "Running in debug mode");
		options.addOption(NOW_OPTION, false, "Triggering all the jobs once on the run");
		options.addOption(HELP_OPTION, false, "help");
		
		try {

			CommandLineParser parser = new GnuParser();
			CommandLine line = parser.parse( options, args );
			boolean isDebug = false;
			boolean isNow = false;
			if (args != null) {
				if (line.hasOption(HELP_OPTION)) {
					HelpFormatter formatter = new HelpFormatter();
					formatter.printHelp( "MailPusher", options );					
					return;
				}
				if (line.hasOption(DEBUG_OPTION)) {
					isDebug = true;
				} 
				if (line.hasOption(NOW_OPTION)) {
					// this will call the trigger for right now
					isNow = true;					
				}

			}
			log.info("############### run context data #############");
			log.info("Current dir: " + System.getProperty("user.dir"));
			File metainf = new File("META-INF");
			if (!metainf.exists()) {
				File resources = new File("../resources");
				System.setProperty("user.dir", resources.getAbsolutePath().replace("\\", "/"));
			}
			log.info("############### reading app context #############");
			context = new FileSystemXmlApplicationContext("file:**/META-INF/ScheduledMailerApplicationContext.xml");
			if (isDebug) {
				IMailService mailservice = (IMailService)context.getBean("mailService");
				mailservice.setDebugMode();
			}

			log.info("############### reading configuration #############");
			IDataResource configResource = (IDataResource)context.getBean("configResource");
			configResource.init();

			log.info("############### init mail items #############");
			List<MailItem> items = configResource.getMailItems();
			for (MailItem item : items) {
				IMailItemJob job = (IMailItemJob)context.getBean("mailItemJob");
				IMailItemJobDetail jobDetails = (IMailItemJobDetail)context.getBean("mailItemJobDetail");
				jobDetails.setItem(item);
				job.init(jobDetails, isNow);
			}
	        
	        if (isDebug || isNow) {
		        log.info("Running in debug mode for 5 minutes only ... ");
		        // wait five minutes to give our jobs a chance to run
		        try {
		            Thread.sleep(300L * 1000L); 
		        } catch (Exception e) {
		        	//
		        }
	        	log.info("Shutting down the scheduler");
		        scheduler = (Scheduler)context.getBean("scheduler");
		        scheduler.shutdown();
		        log.info("Done.");
	        }
	        
	        log.info("################################# Mailer is running. ######################################");
		} catch (Exception e) {
			log.error("Could not start scheduler", e);
			System.exit(-1);
		}
	}
	
	public static Resource getFile(String fileName) {
		return context.getResource(fileName);
	}
	
	public static void stop(String[] args) {
		if (scheduler != null) {
			log.info("###################### Shutting Down #########################");
			try {
				scheduler.shutdown();				
			} catch (Exception e) {
				log.error("Could not stop scheduler", e);
				System.exit(-1);
			}
		}
	}
		
	
}
